<template>
  <div class="db-editor">
    <!-- 面包屑导航 -->
    <BreadcrumbNav
      :current-level="currentLevel"
      :selected-data-source="currentDatasource"
      :selected-database="currentDatabase"
      :selected-table="selectedTableName"
      @navigate="navigateToLevel"
      @refresh="handleRefreshCurrentLevel"
      @go-back="handleGoBack"
    />

    <!-- 级联筛选器 -->
    <div class="cascade-filters">
      <el-select
        v-model="selectedDatasourceId"
        placeholder="选择数据源"
        clearable
        @change="handleDatasourceChange"
        style="width: 200px; margin-right: 10px;"
      >
        <el-option
          v-for="ds in datasources"
          :key="ds.id"
          :label="ds.name"
          :value="ds.id"
        />
      </el-select>
      
      <el-select
        v-model="selectedDatabaseId"
        placeholder="选择数据库实例"
        clearable
        :disabled="!selectedDatasourceId"
        @change="handleDatabaseChange"
        style="width: 200px; margin-right: 10px;"
      >
        <el-option
          v-for="db in databases"
          :key="db.id"
          :label="db.name"
          :value="db.id"
        />
      </el-select>
      
      <el-select
        v-model="selectedTableName"
        placeholder="选择数据表"
        clearable
        :disabled="!selectedDatabaseId"
        @change="handleTableChange"
        style="width: 200px;"
      >
        <el-option
          v-for="table in tables"
          :key="table.name"
          :label="table.name"
          :value="table.name"
        />
      </el-select>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 数据源管理视图 -->
      <div v-if="currentLevel === 'datasource'" class="level-content">
        <DataSourceManager
          :datasources="datasources"
          :loading="datasourcesLoading"
          @select="handleSelectDatasource"
          @add="handleAddDatasource"
          @edit="handleEditDatasource"
          @delete="handleDeleteDatasource"
          @refresh="loadDatasources"
        />
      </div>

      <!-- 数据库实例管理视图 -->
      <div v-else-if="currentLevel === 'database'" class="level-content">
        <DatabaseInstanceManager
          :databases="databases"
          :datasource="currentDatasource"
          :loading="databasesLoading"
          @select="handleSelectDatabase"
          @add="handleAddDatabase"
          @edit="handleEditDatabase"
          @delete="handleDeleteDatabase"
          @refresh="loadDatabases"
          @back="navigateToLevel('datasource')"
        />
      </div>

      <!-- 数据表管理视图 -->
      <div v-else-if="currentLevel === 'table'" class="level-content">
        <div class="table-management-container">
          <div class="sidebar">
            <TableList
              :tables="tables"
              :database="currentDatabase"
              :loading="tablesLoading"
              :current-data-source="selectedDataSource"
              :current-database="selectedDatabase"
              @select-table="handleSelectTable"
              @delete-table="handleDeleteTable"
              @refresh="loadTables"
              @back="navigateToLevel('database')"
            />
          </div>
          
          <div class="content-area">
            <div v-if="!selectedTable" class="empty-state">
              <el-empty description="请选择一个表进行管理">
                <el-button type="primary" @click="handleNewTable">新建表</el-button>
              </el-empty>
            </div>
            
            <div v-else class="table-designer-container">
              <TableDesigner
                :table="selectedTable"
                :database="currentDatabase"
                :is-new="isNewTable"
                @save="handleSaveTable"
                @cancel="handleCancelEdit"
                @preview-sql="handlePreviewSQL"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 默认欢迎页面 -->
      <div v-else class="welcome-page">
        <el-empty description="欢迎使用数据库管理系统">
          <p>请选择数据源开始管理您的数据库</p>
          <el-button type="primary" @click="navigateToLevel('datasource')">
            开始使用
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- SQL预览对话框 -->
    <SQLPreview
      v-model="showSQLDialog"
      :sql="previewSQL"
      :database-type="currentDatabase?.type || 'mysql'"
      @execute="handleExecuteSQL"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataSourceManager from './components/DataSourceManager.vue'
import DatabaseInstanceManager from './components/DatabaseInstanceManager.vue'
import TableList from './components/TableList.vue'
import TableDesigner from './components/TableDesigner.vue'
import BreadcrumbNav from './components/BreadcrumbNav.vue'
import SQLPreview from './components/SQLPreview.vue'

// 当前层级状态
const currentLevel = ref('datasource') // 'datasource' | 'database' | 'table'

// 数据源相关状态
const datasources = ref([])
const datasourcesLoading = ref(false)
const selectedDatasourceId = ref(null)
const currentDatasource = ref(null)

// 数据库实例相关状态
const databases = ref([])
const databasesLoading = ref(false)
const selectedDatabaseId = ref(null)
const currentDatabase = ref(null)

// 数据表相关状态
const tables = ref([])
const tablesLoading = ref(false)
const selectedTableName = ref(null)
const selectedTable = ref(null)
const currentTable = ref(null)
const isNewTable = ref(false)

// SQL预览相关状态
const showSQLDialog = ref(false)
const previewSQL = ref('')

// 导航到指定层级
const navigateToLevel = (level) => {
  currentLevel.value = level
  
  // 清理下级状态
  if (level === 'datasource') {
    currentDatasource.value = null
    currentDatabase.value = null
    currentTable.value = null
    selectedDatasourceId.value = null
    selectedDatabaseId.value = null
    selectedTableName.value = null
    databases.value = []
    tables.value = []
  } else if (level === 'database') {
    currentDatabase.value = null
    currentTable.value = null
    selectedDatabaseId.value = null
    selectedTableName.value = null
    tables.value = []
  } else if (level === 'table') {
    currentTable.value = null
    selectedTableName.value = null
  }
}

// 数据源管理方法
const loadDatasources = async () => {
  datasourcesLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    datasources.value = [
      {
        id: '1',
        name: '生产环境MySQL',
        type: 'mysql',
        host: 'prod-mysql.example.com',
        port: 3306,
        status: 'connected',
        description: '生产环境主数据库'
      },
      {
        id: '2',
        name: '测试环境PostgreSQL',
        type: 'postgresql',
        host: 'test-pg.example.com',
        port: 5432,
        status: 'disconnected',
        description: '测试环境数据库'
      },
      {
        id: '3',
        name: '开发环境MySQL',
        type: 'mysql',
        host: 'dev-mysql.example.com',
        port: 3306,
        status: 'connected',
        description: '开发环境数据库'
      }
    ]
  } catch (error) {
    ElMessage.error('加载数据源失败')
  } finally {
    datasourcesLoading.value = false
  }
}

const handleSelectDatasource = (datasource) => {
  currentDatasource.value = datasource
  selectedDatasourceId.value = datasource.id
  navigateToLevel('database')
  loadDatabases()
}

const handleAddDatasource = () => {
  ElMessage.info('添加数据源功能开发中...')
}

const handleEditDatasource = (datasource) => {
  ElMessage.info(`编辑数据源: ${datasource.name}`)
}

const handleDeleteDatasource = async (datasource) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据源 "${datasource.name}" 吗？`,
      '确认删除',
      { type: 'warning' }
    )
    datasources.value = datasources.value.filter(ds => ds.id !== datasource.id)
    ElMessage.success('数据源删除成功')
  } catch {
    // 用户取消
  }
}

const handleDatasourceChange = (datasourceId) => {
  if (datasourceId) {
    const datasource = datasources.value.find(ds => ds.id === datasourceId)
    if (datasource) {
      handleSelectDatasource(datasource)
    }
  } else {
    // 清空选择，回到数据源层级
    selectedDatasourceId.value = null
    selectedDatabaseId.value = null
    selectedTableName.value = null
    currentDatasource.value = null
    currentDatabase.value = null
    currentTable.value = null
    navigateToLevel('datasource')
  }
}

// 数据库实例管理方法
const loadDatabases = async () => {
  if (!currentDatasource.value) return
  
  databasesLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 600))
    databases.value = [
      {
        id: '1',
        name: 'ecommerce_prod',
        type: currentDatasource.value.type,
        size: '2.5GB',
        tables: 25,
        status: 'active',
        description: '电商系统生产数据库'
      },
      {
        id: '2',
        name: 'user_center',
        type: currentDatasource.value.type,
        size: '800MB',
        tables: 12,
        status: 'active',
        description: '用户中心数据库'
      },
      {
        id: '3',
        name: 'analytics',
        type: currentDatasource.value.type,
        size: '5.2GB',
        tables: 45,
        status: 'readonly',
        description: '数据分析数据库'
      }
    ]
  } catch (error) {
    ElMessage.error('加载数据库实例失败')
  } finally {
    databasesLoading.value = false
  }
}

const handleSelectDatabase = (database) => {
  currentDatabase.value = database
  selectedDatabaseId.value = database.id
  navigateToLevel('table')
  loadTables()
}

const handleAddDatabase = () => {
  ElMessage.info('添加数据库实例功能开发中...')
}

const handleEditDatabase = (database) => {
  ElMessage.info(`编辑数据库实例: ${database.name}`)
}

const handleDeleteDatabase = async (database) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据库实例 "${database.name}" 吗？`,
      '确认删除',
      { type: 'warning' }
    )
    databases.value = databases.value.filter(db => db.id !== database.id)
    ElMessage.success('数据库实例删除成功')
  } catch {
    // 用户取消
  }
}

const handleDatabaseChange = (databaseId) => {
  if (databaseId) {
    const database = databases.value.find(db => db.id === databaseId)
    if (database) {
      handleSelectDatabase(database)
    }
  } else {
    // 清空数据库和表的选择，回到数据库层级
    selectedDatabaseId.value = null
    selectedTableName.value = null
    currentDatabase.value = null
    currentTable.value = null
    navigateToLevel('database')
  }
}

// 数据表管理方法
const loadTables = async () => {
  if (!currentDatabase.value) return
  
  tablesLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    tables.value = [
      {
        name: 'users',
        comment: '用户表',
        columns: 8,
        rows: 15420,
        size: '2.1MB',
        engine: 'InnoDB'
      },
      {
        name: 'products',
        comment: '商品表',
        columns: 12,
        rows: 3250,
        size: '1.8MB',
        engine: 'InnoDB'
      },
      {
        name: 'orders',
        comment: '订单表',
        columns: 15,
        rows: 8960,
        size: '4.2MB',
        engine: 'InnoDB'
      },
      {
        name: 'categories',
        comment: '分类表',
        columns: 6,
        rows: 120,
        size: '64KB',
        engine: 'InnoDB'
      }
    ]
  } catch (error) {
    ElMessage.error('加载数据表失败')
  } finally {
    tablesLoading.value = false
  }
}

const handleSelectTable = (table) => {
  selectedTable.value = table
  currentTable.value = table
  selectedTableName.value = table.name
  isNewTable.value = false
}

const handleDeleteTable = async (tableName) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除表 "${tableName}" 吗？此操作不可恢复。`,
      '确认删除',
      { type: 'warning' }
    )
    tables.value = tables.value.filter(t => t.name !== tableName)
    if (selectedTable.value?.name === tableName) {
      selectedTable.value = null
      currentTable.value = null
      selectedTableName.value = null
    }
    ElMessage.success('表删除成功')
  } catch {
    // 用户取消
  }
}

const handleNewTable = () => {
  selectedTable.value = {
    name: '',
    comment: '',
    columns: [],
    indexes: []
  }
  isNewTable.value = true
}

const handleSaveTable = async (tableData) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isNewTable.value) {
      tables.value.push({
        name: tableData.name,
        comment: tableData.comment,
        columns: tableData.columns.length,
        rows: 0,
        size: '0KB',
        engine: 'InnoDB'
      })
      ElMessage.success('表创建成功')
    } else {
      const index = tables.value.findIndex(t => t.name === tableData.name)
      if (index !== -1) {
        tables.value[index] = {
          ...tables.value[index],
          comment: tableData.comment,
          columns: tableData.columns.length
        }
      }
      ElMessage.success('表更新成功')
    }
    
    isNewTable.value = false
    loadTables()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const handleCancelEdit = () => {
  selectedTable.value = null
  currentTable.value = null
  isNewTable.value = false
}

const handleTableChange = (tableName) => {
  if (tableName) {
    const table = tables.value.find(t => t.name === tableName)
    if (table) {
      handleSelectTable(tableName)
    }
  } else {
    // 清空表的选择，保持在表层级
    selectedTableName.value = null
    selectedTable.value = null
    currentTable.value = null
  }
}

// SQL预览相关方法
const handlePreviewSQL = (sql) => {
  previewSQL.value = sql
  showSQLDialog.value = true
}

const handleExecuteSQL = async (sql) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('SQL执行成功')
    showSQLDialog.value = false
    loadTables()
  } catch (error) {
    ElMessage.error('SQL执行失败')
  }
}

// 面包屑导航相关方法
const handleRefreshCurrentLevel = () => {
  switch (currentLevel.value) {
    case 'datasource':
      loadDatasources()
      break
    case 'database':
      loadDatabases()
      break
    case 'table':
      loadTables()
      break
  }
}

const handleGoBack = (targetLevel) => {
  navigateToLevel(targetLevel)
}

// 监听器
watch(currentLevel, (newLevel) => {
  if (newLevel === 'datasource' && datasources.value.length === 0) {
    loadDatasources()
  }
})

// 组件挂载时初始化
onMounted(() => {
  loadDatasources()
})
</script>

<style scoped>
.db-editor {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 面包屑导航 */
.breadcrumb-nav {
  background: white;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.breadcrumb-nav :deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #409eff;
  font-weight: 500;
}

/* 级联筛选器 */
.cascade-filters {
  background: white;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.level-content {
  flex: 1;
  overflow: hidden;
  background: white;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表管理容器 */
.table-management-container {
  height: 100%;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 320px;
  background: #fafbfc;
  border-right: 1px solid #e4e7ed;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content-area {
  flex: 1;
  background: white;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-designer-container {
  flex: 1;
  overflow: hidden;
}

/* 欢迎页面 */
.welcome-page {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: white;
  text-align: center;
}

.welcome-page p {
  margin: 16px 0;
  color: #606266;
  font-size: 14px;
}

/* 空状态 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: white;
  text-align: center;
}

/* 级联筛选器响应式 */
@media (max-width: 1200px) {
  .cascade-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .cascade-filters .el-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
  
  .cascade-filters .el-select:last-child {
    margin-bottom: 0;
  }
}

/* 表管理容器响应式 */
@media (max-width: 768px) {
  .table-management-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: 250px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .level-content {
    margin: 8px;
  }
  
  .cascade-filters {
    padding: 12px 16px;
  }
  
  .breadcrumb-nav {
    padding: 8px 16px;
  }
}

/* 小屏幕优化 */
@media (max-width: 480px) {
  .cascade-filters .el-select {
    font-size: 14px;
  }
  
  .breadcrumb-nav {
    font-size: 12px;
  }
  
  .level-content {
    margin: 4px;
    border-radius: 4px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .db-editor {
    background: #1a1a1a;
  }
  
  .breadcrumb-nav,
  .cascade-filters,
  .level-content,
  .content-area,
  .welcome-page,
  .empty-state {
    background: #2d2d2d;
    color: #e4e7ed;
  }
  
  .sidebar {
    background: #252525;
  }
  
  .breadcrumb-nav,
  .cascade-filters {
    border-bottom-color: #404040;
  }
  
  .sidebar {
    border-right-color: #404040;
  }
  
  .level-content {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  }
}

/* 动画效果 */
.level-content {
  transition: all 0.3s ease;
}

.cascade-filters .el-select {
  transition: all 0.2s ease;
}

.cascade-filters .el-select:hover {
  transform: translateY(-1px);
}

/* 滚动条样式 */
.sidebar::-webkit-scrollbar,
.content-area::-webkit-scrollbar {
  width: 6px;
}

.sidebar::-webkit-scrollbar-track,
.content-area::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.sidebar::-webkit-scrollbar-thumb,
.content-area::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.sidebar::-webkit-scrollbar-thumb:hover,
.content-area::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>